package veetouch.shareimage;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;

import veetouch.network.NetworkConncetion;
import veetouch.syncpc.R;
import veetouch.syncpc.VtAndroidSyncActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Gallery;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;

public class ShareImageActivity  extends Activity 
{
	private NetworkConncetion network;
	
	// private Uri[] mUrls;
    private ArrayList<Uri> mUrls;
	private String[] mFiles = null;
    
    private Gallery gallery;
    private ImageAdapter imageAdapter;
    private ImageView imageView;
    private Button shareButton;
    
    private String imageSharePath = "";
    private BitmapFactory.Options bitmap_opts;
    
	@Override
    public void onCreate(Bundle savedInstanceState) 
    {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.image);
		
		// Preparation step
		this.bitmap_opts = new BitmapFactory.Options();
		this.bitmap_opts.inSampleSize = 8;
		this.bitmap_opts.inDither = false; 			//Disable Dithering mode
		this.bitmap_opts.inPurgeable = true; 		//Tell to gc that whether it needs free memory, the Bitmap can be cleared
		//this.bitmap_opts.inInputShareable = true;	//Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
		//this.bitmap_opts.inTempStorage = new byte[16 * 1024];
		
		// 1. Set Toolbar
		Button menu = (Button) findViewById(R.id.meuButton);
		menu.setOnClickListener(new OnClickListener() 
		{
			public void onClick(View view) 
			{
				// Send close socket message;
				network.sendExitMessage();
				// Close network socket
				network.closeConnection();
				// Back to main page
				Intent intent = new Intent(view.getContext(),VtAndroidSyncActivity.class);
				startActivity(intent);
			}
		});
		
		// 2. Set Network
		Bundle extras = getIntent().getExtras();
		if (extras == null) 
		{
			return;
		}
		this.network = new NetworkConncetion(this);
        this.network.setAddress(extras.getString("address"));
        this.network.setPort(extras.getInt("port"));
        this.network.openConnection();
		
        // 3. Set Image Browser and Display
		this.shareButton = (Button) findViewById(R.id.button1);
		this.shareButton.setEnabled(false);
		this.shareButton.setOnClickListener(new OnClickListener() 
		{
			public void onClick(View arg0) {
				if(imageSharePath != "")
				{
					network.sendImage(imageSharePath);
				}
			}
		});
		
		// Load all file from android
		File images = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM+"/Camera");
		File[] imagelist = images.listFiles(new FilenameFilter(){
        	
            public boolean accept(File dir, String name)  
            {  
                return ((name.endsWith(".jpg"))||(name.endsWith(".png")));  
            }
        });
		if(imagelist == null)
		{
			imagelist = new File[0];
		}
		File images2 = new File("/sdcard/vSync/");
		File[] imagelist2 = images2.listFiles(new FilenameFilter(){
        	
            public boolean accept(File dir, String name)  
            {  
                return ((name.endsWith(".jpg"))||(name.endsWith(".png")));  
            }
        });
		if(imagelist2 == null)
		{
			imagelist2 = new File[0];
		}
		imagelist = ShareImageActivity.concat(imagelist, imagelist2);

        mFiles = new String[imagelist.length];
        for(int i= 0 ; i< imagelist.length; i++)  
        {  
            mFiles[i] = imagelist[i].getAbsolutePath();  
        }
        
        this.mUrls = new ArrayList<Uri>();
        for(int i=0; i < mFiles.length; i++)  
        {
        	this.mUrls.add(Uri.parse(mFiles[i]));
        }
        
        this.gallery = (Gallery) findViewById(R.id.gallery1);
        this.imageAdapter = new ImageAdapter(this);
        this.gallery.setAdapter(this.imageAdapter);
 
        this.imageView = (ImageView)findViewById(R.id.imageView1);
        this.gallery.setOnItemClickListener(new OnItemClickListener() 
        {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) 
			{
				imageSharePath = mUrls.get(arg2).getPath();
				Bitmap bm = BitmapFactory.decodeFile(mUrls.get(arg2).getPath(),bitmap_opts);
				imageView.setImageBitmap(bm);
				if(network.isConnect())
				{
					shareButton.setEnabled(true);
				}
				else
				{
					onCreateDialog(0);
				}
			}
        });
    }
	
	public void addNewImageToGallery(String url)
	{
		this.imageAdapter.addNewImage(url);
		//this.gallery.refreshDrawableState(); // Re draw all image
		this.imageAdapter.notifyDataSetChanged();
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateDialog(int)
	 * 	case:
	 * 		0 	- Network lost connection
	 * 		1	- Get image from server
	 */
	@Override
	protected Dialog onCreateDialog(int id) 
	{
		Builder builder;
		AlertDialog dialog;
		switch (id) {
			case 0:
				builder = new AlertDialog.Builder(this);
				builder.setMessage("Can not connect to Server.\nPlease check wifi connection.");
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() 
				{
	                public void onClick(DialogInterface dialog, int which) 
	                {
	                	// Back to main page
	    				Intent intent = new Intent(getApplicationContext(),VtAndroidSyncActivity.class);
	    				startActivity(intent);
	                }
	            });
				dialog = builder.create();
	            dialog.show();
	            break;
			case 1:
				builder = new AlertDialog.Builder(this);
				// builder.setIcon();
				builder.setMessage("Get image frome Server.");
				builder.setCancelable(true);
				builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int which) {
	                	// Save temp file into Camera
	                	
	                }
	            });
				builder.setNegativeButton("Discard", new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int which) {
	                    
	                }
	            });
				dialog = builder.create();
	            dialog.show();
	            break;
		}
		return super.onCreateDialog(id);
	}
	
	public void surfaceDestroyed(SurfaceHolder arg0) 
	{
		if(this.network != null)
		{
			this.network.closeConnection();
			// this.network.runProcess = false;
			// this.network.stop(new Throwable());
		}
		this.finish();
	}
	
	public static File[] concat(File[] allData, File[] data) 
	{
		File[] result = new File[allData.length + data.length];
		System.arraycopy(allData, 0, result, 0, allData.length);
		System.arraycopy(data, 0, result, allData.length, data.length);
		return result;
	}
	
	public class ImageAdapter extends BaseAdapter 
	{
		private ArrayList<Bitmap> imageList;
		
    	private Context ctx;
    	int imageBackground;
    	private BitmapFactory.Options opts;
    	
    	public ImageAdapter(Context c) {
			ctx = c;
			this.opts = new BitmapFactory.Options();
			this.opts.inSampleSize = 16;
			this.opts.inDither = false; //Disable Dithering mode
			
			this.imageList = new ArrayList<Bitmap>();
			for (Uri uri : mUrls) 
			{
				Bitmap bm = BitmapFactory.decodeFile(uri.getPath(),this.opts);
				this.imageList.add(bm);
			}
			
			TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);
			imageBackground = ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 0);
			ta.recycle();
		}
    	
    	public void addNewImage(String url)
    	{
    		mUrls.add(Uri.parse(url));
    		Bitmap bm = BitmapFactory.decodeFile(url,this.opts);
    		this.imageList.add(bm);
    	}

    	public int getCount() 
    	{	
    		//return mUrls.length;
    		return this.imageList.size();
    	}

    	public Bitmap getItem(int arg0) {
    		
    		return this.imageList.get(arg0);
    	}

    	public long getItemId(int arg0) {
    		
    		return arg0;
    	}

    	public View getView(int arg0, View arg1, ViewGroup arg2) {
    		ImageView iv = new ImageView(ctx);
    		// Old style
    		//Bitmap bm = BitmapFactory.decodeFile(mUrls[arg0].getPath(),this.opts);
    		Bitmap bm = this.imageList.get(arg0);
    		iv.setImageBitmap(bm);
    		//iv.setLayoutParams(new Gallery.LayoutParams(150,120));
    		iv.setLayoutParams(new Gallery.LayoutParams(75,60));
    		iv.setScaleType(ImageView.ScaleType.FIT_XY);
    		iv.setBackgroundResource(imageBackground);
    		
    		return iv;
    	}
    }
}
